import { createI18n } from 'vue-i18n';

import storage from '@/utils/storage';

const localPathPrefix = '../locale/';

const messages = Object.fromEntries(
  Object.entries(import.meta.globEager('../locale/*.ts')).map(
    ([key, value]) => {
      // @ts-ignore
      return [key.slice(localPathPrefix.length, -3), value.default];
    }
  )
);

// 支持的语言
const supportLang = [
  'en',
  'ja',
  'ko',
  'id',
  'vi',
  'zh_tw',
  'ar',
  'es',
  'fr',
  'hi',
  'pt',
  'ru',
  'th',
  'zh_cn',
];
let locale;
if (storage.getItem('lang') === undefined) {
  storage.setItem('lang', 'en');
  locale = 'en';
} else {
  if (supportLang.includes(storage.getItem('lang'))) {
    locale = storage.getItem('lang');
  } else {
    storage.setItem('lang', 'en');
    locale = 'en';
  }
}

// if (location.pathname !== '/') {
//   const newLang = location.pathname.substring(
//     location.pathname.lastIndexOf('/') + 1,
//     location.pathname.length
//   )
//   console.log('newLang', newLang)
//   locale = newLang
//   if (newLang !== storage.getItem('lang')) {
//     storage.setItem('lang', newLang)
//   }
// } else {
//   if (storage.getItem('lang') === '' || storage.getItem('lang') === undefined) {
//     storage.setItem('lang', 'en')
//     locale = 'en'
//   } else {
//     locale = storage.getItem('lang')
//   }
// }
console.log('locale:', locale);

const i18n = createI18n({
  legacy: false,
  locale,
  globalInjection: true,
  messages,
});
document.getElementsByTagName('html')[0].setAttribute('lang', locale);

export default i18n;
